package com.wlstock.funi.runnable;

import com.tencent.bugly.crashreport.CrashReport;
import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.PositionDao;
import com.wlstock.funi.model.PositionModel;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.ToastUtils;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CurPosition implements TaskResultListener<String> {
	public static String POSITION_TOTALMONEY = "POSITION_TOTALMONEY";//总资产
	public static String POSITION_AVAIBLE    = "POSITION_AVAIBLE";//可用资金
	public static String POSITION_STOCKMONEY  = "POSTION_STOCKMONEY";//持仓金额
	public CurPositionListener resultListener;  
	public CurPosition(){
		
	}

	public void requset(CurPositionListener listener){
		this.resultListener = listener;
		requset();
	}

	public void requset(){
		if (!FundApplication.isLogSuccess){
			return;
		}

		StringBuffer sb = new StringBuffer();
//		https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getFunds
		sb.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getFundsList");
		FundAsyTask<String, Void, String> task = new FundAsyTask<String, Void, String>();
		task.backListener = new TaskLitener<String,String>() {

			@Override
			public String doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();
				
				HttpGet hGet = new HttpGet(params[0]);
				hGet.addHeader("Accept","*/*");
				hGet.addHeader("Accept-Encoding","gzip, deflate");
				hGet.addHeader("Cache-Control","max-age=0");
				hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
				hGet.addHeader("Connection","keep-alive");
				hGet.addHeader("Cookie",FundApplication.cookie);
				hGet.addHeader("Content-Type","text/plain;charset=UTF-8");
				hGet.addHeader("Upgrade-Insecure-Requests","1");
				hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
				hGet.addHeader("X-Requested-With","XMLHttpRequest");
				hGet.addHeader("Cookie",FundApplication.cookie);
				
//			    </tr>
//			            <tr class="odd" align="right">
//			                <td>人民币</td>
//			                <td>9280.85</td>//当前余额
//			                <td>9280.85</td>//期初资金
//			                <td>56282.91</td>//可用资金
//			                <td>0</td>//禁取资金
//			                <td>0</td>//禁取资产
//			                <td>0</td>//交易冻结
//			                <td>9280.85</td>//解冻资金
//			                <td>9280.85</td>//证券市值
//			                <td>55950.00</td>//证券市值
//			                <td>65230.85</td>//资产值
//			                <td>84641.50</td>//利息积数
//			                <td>0.71</td>//预计利息
//			                <td>0</td>//预计罚息
//			                <td>0</td>//资产管理佣金
//			                <td>9280.85</td>//总资金余额
//			                <td>0</td>//基金市值
//			            </tr>
				try {
					HttpResponse response = client.execute(hGet);
					
					if (response.getStatusLine().getStatusCode() == 200) {
						String result = IOUtils.is2Str(response.getEntity().getContent());
						return result;
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				} catch (Exception e) {
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				}finally{
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};
		
		task.resultListener = this;
		task.execute(sb.toString());
		
	}

	@Override
	public void onPostResult(String result) {
		if (result!=null) {
			Pattern compile = Pattern.compile("<td>[0-9]*.[0-9]*</td>");
			Matcher matcher = compile.matcher(result);
			ArrayList<String> resultList = new ArrayList<String>();
			while(matcher.find()){
				String matchResult = result.substring(matcher.start()+4, matcher.end()-5);
				resultList.add(matchResult);
			}
			if (resultList.size() == 16) {
//			                <td>9280.85</td>//当前余额
//			                <td>9280.85</td>//期初资金
//			                <td>56282.91</td>//可用资金
//			                <td>0</td>//禁取资金
//			                <td>0</td>//禁取资产
//			                <td>0</td>//交易冻结
//			                <td>9280.85</td>//解冻资金
//			                <td>9280.85</td>//证券市值
//			                <td>55950.00</td>//证券市值
//			                <td>65230.85</td>//资产值
//			                <td>84641.50</td>//利息积数
//			                <td>0.71</td>//预计利息
//			                <td>0</td>//预计罚息
//			                <td>0</td>//资产管理佣金
//			                <td>9280.85</td>//总资金余额
//			                <td>0</td>//基金市值
				PositionModel model = new PositionModel();
				model.setUseableFund(Float.valueOf(resultList.get(2)));
				model.setStockMoney(Float.valueOf(resultList.get(7)));
				model.setTotalAsserts(Float.valueOf(resultList.get(9)));
				model.setOwner(PositionModel.ME);
				PositionDao.getInstance(FundApplication.getInstance()).addOrUpdatePosition(model);
				ToastUtils.showMiddleMsg(FundApplication.getInstance(), "刷新仓位信息成功");
				NotiUtils.cancelNoti(FundApplication.getInstance(),NotiIdGenerator.ID_PARSE_POSITION_STATE);
				if (resultListener!=null){
					resultListener.getPosition(model);
				}
			}else{
				reqAssets(this.resultListener);
			}
		}
	}

	private void reqAssets(CurPositionListener listener){
		this.resultListener = listener;
		reqAssets();
	}

	//只是查询总资产,然后用我的持股信息填充
	private void reqAssets(){
		if (!FundApplication.isLogSuccess){
			return;
		}

		StringBuffer sb = new StringBuffer();
		sb.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getFunds");
		FundAsyTask<String, Void, String> task = new FundAsyTask<String, Void, String>();
		task.backListener = new TaskLitener<String,String>() {

			@Override
			public String doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();

				HttpPost hGet = new HttpPost(params[0]);
				hGet.addHeader("Accept","*/*");
				hGet.addHeader("Accept-Encoding","gzip, deflate, br");
				hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
				hGet.addHeader("Connection","keep-alive");
				hGet.addHeader("Cookie",FundApplication.cookie);
				hGet.addHeader("Content-Type","text/plain;charset=UTF-8");
				hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
				hGet.addHeader("X-Requested-With","XMLHttpRequest");
				hGet.addHeader("Cookie",FundApplication.cookie);

				try {
					HttpResponse response = client.execute(hGet);

					if (response.getStatusLine().getStatusCode() == 200) {
						String result = IOUtils.is2Str(response.getEntity().getContent());
						return result;
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				} catch (Exception e) {
					e.printStackTrace();
					CrashReport.postCatchedException(e);
				}finally{
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};

		task.resultListener = new TaskResultListener<String>() {
			@Override
			public void onPostResult(String result) {
				if (result!=null) {
					Pattern compile = Pattern.compile("<td>[0-9]*.[0-9]*</td>");
					Matcher matcher = compile.matcher(result);
					ArrayList<String> resultList = new ArrayList<String>();
					while(matcher.find()){
						String matchResult = result.substring(matcher.start()+4, matcher.end()-5);
						resultList.add(matchResult);
					}
//					<td>8405.26</td>  可用资金
//					<td>30406.22</td> 可用余额(当天卖出的时候这个不准)
//					<td>43814.00</td> 持仓市值(加上1天报价之类)
//					<td>52219.26</td> 总市值
					if (resultList.size() == 4) {//???这里需要重新设置
						float totalAssert = Float.valueOf(resultList.get(3));
						//判断是否是新的,在15分钟之内
						PositionModel model = null;
						if (MyAccountStockDao.getInstance(FundApplication.getInstance()).isMyAccountNewly(new Date(), 10)){
							model = new PositionModel();
							model.setTotalAsserts(totalAssert);
							float stockMoney = MyAccountStockDao.getInstance(FundApplication.getInstance()).queryMyAccountTotalFund();
							model.setStockMoney(stockMoney);
							model.setUseableFund(totalAssert-stockMoney);
							model.setOwner(PositionModel.ME);
						}else{
							//只更新总市值
							model = PositionDao.getInstance(FundApplication.getInstance()).getCurpositionModel();
							model.setTotalAsserts(totalAssert);
							model.setLastUpdate(new Date());
						}

						PositionDao.getInstance(FundApplication.getInstance()).addOrUpdatePosition(model);


						ToastUtils.showMiddleMsg(FundApplication.getInstance(), "刷新仓位信息成功");
						NotiUtils.cancelNoti(FundApplication.getInstance(),NotiIdGenerator.ID_PARSE_POSITION_STATE);
						if (resultListener!=null){
							resultListener.getPosition(model);
						}
					}else{
						NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_PARSE_POSITION_STATE, "仓位回调解析失败", "请重新登录", R.drawable.ic_exception);
					}
				}
			}
		};
		task.execute(sb.toString());

	}
	
	public interface CurPositionListener{
		public void getPosition(PositionModel model);
	}
	
}
